package io;

import java.io.*;
import java.util.Scanner;

public class IODemo10 {
    // 遍历目录查看关键字  类似于全文搜索

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入目录");
        String record = scanner.next();
        File file = new File(record);
        System.out.println("输入关键字");
        String word = scanner.next();

        scanDir(file,word);
    }

    private static void scanDir(File file, String word) {
        File[] files = file.listFiles();
        if (files == null) {
            return ;
        }
        for (File f : files) {
            if (f.isFile()) {
                System.out.println(f.getAbsolutePath());
                if (scanFile(f,word) .contains(word)) {
                    System.out.println(f.getAbsolutePath() + " 包含该关键字");
                }
            } else if (f.isDirectory()) {
                scanDir(f,word);
            } else {
                continue;
            }
        }
    }

    private static String scanFile(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {

            while (true) {
                int c = 0;
                c = reader.read();
                if (c == -1) {
                    break;
                }
                stringBuilder.append((char)c);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }
}
